package com.hyfd.common.utils;

import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class Sign {
	
	private static Logger logger = Logger.getLogger(Sign.class);
	
	public static String sign(String signKey,JsonObject... jsonObjects) {
		StringBuffer sb = new StringBuffer();

		Map<String, String> attrs = new TreeMap<String, String>();
		for (JsonObject obj : jsonObjects) {
			for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
				String key = entry.getKey();
				String value = entry.getValue().getAsString();
				if (value != null && !"".equals(value.trim())) {
					attrs.put(key, value);
				}
			}
		}

		Set<Map.Entry<String, String>> es = attrs.entrySet();
		Iterator<Map.Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = it.next();
			String key = entry.getKey();
			String value = entry.getValue();
			sb.append(key).append("=").append(value).append("&");
		}
		sb.deleteCharAt(sb.length() - 1).append(signKey);
		logger.info("签名前串：{}"+sb.toString());
		String sign = DigestUtils.md5Hex(sb.toString().getBytes(Charset.forName("UTF-8")));
		logger.info("签名：{}"+sign);
		return sign;
	}
}
